import { useRobotStore } from '../stores/robotStore'

class WebSocketManager {
  constructor() {
    this.ws = null
    this.reconnectAttempts = 0
    this.maxReconnectAttempts = 5
    this.reconnectInterval = 3000
    this.heartbeatInterval = null
    this.robotStore = null
  }

  connect(url = 'ws://localhost:8000/ws') {
    try {
      this.ws = new WebSocket(url)
      this.robotStore = useRobotStore()
      
      this.ws.onopen = this.onOpen.bind(this)
      this.ws.onmessage = this.onMessage.bind(this)
      this.ws.onclose = this.onClose.bind(this)
      this.ws.onerror = this.onError.bind(this)
      
    } catch (error) {
      console.error('WebSocket连接失败:', error)
    }
  }

  onOpen(event) {
    console.log('WebSocket连接已建立')
    this.reconnectAttempts = 0
    
    // 开始心跳
    this.startHeartbeat()
    
    // 更新连接状态
    if (this.robotStore) {
      this.robotStore.connectionState.isConnected = true
      this.robotStore.connectionState.lastHeartbeat = new Date().toISOString()
    }
  }

  onMessage(event) {
    try {
      const data = JSON.parse(event.data)
      this.handleMessage(data)
    } catch (error) {
      console.error('解析WebSocket消息失败:', error)
    }
  }

  onClose(event) {
    console.log('WebSocket连接已关闭:', event.code, event.reason)
    
    // 停止心跳
    this.stopHeartbeat()
    
    // 更新连接状态
    if (this.robotStore) {
      this.robotStore.connectionState.isConnected = false
    }
    
    // 尝试重连
    if (this.reconnectAttempts < this.maxReconnectAttempts) {
      setTimeout(() => {
        this.reconnectAttempts++
        console.log(`尝试重连 (${this.reconnectAttempts}/${this.maxReconnectAttempts})`)
        this.connect()
      }, this.reconnectInterval)
    }
  }

  onError(error) {
    console.error('WebSocket错误:', error)
  }

  handleMessage(data) {
    if (!this.robotStore) return

    switch (data.type) {
      case 'robot_status':
        this.handleRobotStatus(data.payload)
        break
      
      case 'robot_position':
        this.handleRobotPosition(data.payload)
        break
      
      case 'task_update':
        this.handleTaskUpdate(data.payload)
        break
      
      case 'camera_frame':
        this.handleCameraFrame(data.payload)
        break
      
      case 'system_alert':
        this.handleSystemAlert(data.payload)
        break
      
      case 'heartbeat':
        this.handleHeartbeat(data.payload)
        break
      
      default:
        console.log('未知消息类型:', data.type)
    }
  }

  handleRobotStatus(payload) {
    const { status, battery, posture, isMoving, direction } = payload
    
    this.robotStore.updateStatus(status)
    this.robotStore.updateBattery(battery)
    this.robotStore.setPosture(posture)
    
    if (isMoving) {
      this.robotStore.startMovement(direction)
    } else {
      this.robotStore.stopMovement()
    }
  }

  handleRobotPosition(payload) {
    const { x, y, z } = payload
    this.robotStore.updatePosition(x, y, z)
  }

  handleTaskUpdate(payload) {
    const { taskId, status, result } = payload
    this.robotStore.updateTaskStatus(taskId, status, result)
  }

  handleCameraFrame(payload) {
    // 处理摄像头帧数据
    const { cameraId, frameData } = payload
    // 这里可以更新摄像头显示
  }

  handleSystemAlert(payload) {
    const { level, message, timestamp } = payload
    console.log(`系统警告 [${level}]: ${message}`)
    
    // 可以触发UI通知
    if (level === 'error' || level === 'critical') {
      // 显示错误通知
    }
  }

  handleHeartbeat(payload) {
    if (this.robotStore) {
      this.robotStore.connectionState.lastHeartbeat = new Date().toISOString()
      this.robotStore.connectionState.signalStrength = payload.signalStrength || 95
    }
  }

  startHeartbeat() {
    this.heartbeatInterval = setInterval(() => {
      if (this.ws && this.ws.readyState === WebSocket.OPEN) {
        this.send({
          type: 'heartbeat',
          timestamp: new Date().toISOString()
        })
      }
    }, 30000) // 30秒心跳
  }

  stopHeartbeat() {
    if (this.heartbeatInterval) {
      clearInterval(this.heartbeatInterval)
      this.heartbeatInterval = null
    }
  }

  send(data) {
    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
      this.ws.send(JSON.stringify(data))
    } else {
      console.warn('WebSocket未连接，无法发送消息')
    }
  }

  // 发送机器狗控制指令
  sendRobotCommand(command, params = {}) {
    this.send({
      type: 'robot_command',
      command,
      params,
      timestamp: new Date().toISOString()
    })
  }

  // 发送摄像头控制指令
  sendCameraCommand(cameraId, command, params = {}) {
    this.send({
      type: 'camera_command',
      cameraId,
      command,
      params,
      timestamp: new Date().toISOString()
    })
  }

  // 发送AI指令
  sendAICommand(command, type = 'text') {
    this.send({
      type: 'ai_command',
      command,
      commandType: type,
      timestamp: new Date().toISOString()
    })
  }

  disconnect() {
    this.stopHeartbeat()
    
    if (this.ws) {
      this.ws.close()
      this.ws = null
    }
  }
}

// 创建全局WebSocket管理器实例
export const wsManager = new WebSocketManager()

// 自动连接
export const connectWebSocket = (url) => {
  wsManager.connect(url)
}

// 断开连接
export const disconnectWebSocket = () => {
  wsManager.disconnect()
}

export default wsManager